<template>
    <div>
        <div class="addressList" v-show="!addShow">
            <van-address-list v-model="chosenAddressId" :list="list" default-tag-text="默认" @add="onAdd" @edit="onEdit" />
        </div>
        <div class="addressAdd" v-show="addShow">
            <van-address-edit :area-list="areaList" show-delete show-set-default show-search-result
                :search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave"
                @delete="onDelete" delete-button-text="返回" :address-info="addressinfo" />
        </div>
    </div>
</template>

<script>
import Vue from 'vue';
import { AddressList } from 'vant';
import { AddressEdit } from 'vant';
import { Toast } from 'vant';
import { areaList } from '@vant/area-data';
import { Area } from 'vant';
import { getAddress, addAddress, editAddress } from '@/request/request'
import { getCookie } from '@/utils/cookie'

Vue.use(Area);
Vue.use(AddressEdit);
Vue.use(AddressList);
export default {
    created() {
        getAddress().then(data => this.list = data)
    },
    data() {
        return {
            chosenAddressId: '1',
            list: [],
            addShow: false,
            areaList,
            searchResult: [],
            addressinfo: {}
        };

    },
    methods: {
        onAdd() {
            this.addShow = true;
        },
        onEdit(item, index) {
            this.addShow = true;
            this.addressinfo = item
            console.log(this.addressinfo);
        },
        onSave(content) {
            console.log(this.addressinfo);
            if (JSON.stringify(this.addressinfo) === '{}') {
                console.log(222);
                addAddress({
                    username: getCookie('username'),
                    ...content,
                    address: content.province + content.city + content.county + content.addressDetail
                }).then(data => {
                    Toast({
                        message: '添加成功！',
                        onClose: () => {
                            this.addShow = false;
                            getAddress().then(data => this.list = data)
                        }
                    });
                })
            } else {
                //修改
                editAddress(content).then(data => {
                    Toast({
                        message: '修改成功！',
                        onClose: () => {
                            this.addressinfo = {}
                            this.addShow = false;
                            getAddress().then(data => this.list = data)
                        }
                    });
                })
            }
        },
        onDelete() {
            this.addShow = false;
        }
    }
}
</script>

<style></style>
